有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在用户输入小于0的数字时中断扫描仪?

问题

嘿,伙计们,我的问题是如何将扫描对象中的整数附加到数组中。需要注意的是,一旦整数小于0,扫描仪就应该停止获取整数值。换句话说,无论输入的数组有多长,一旦扫描仪检测到负值,它都应该停止接受整数值这个问题使用的是Java语言

从那里,它应该打印出输入的数组


例如:

当输入是

12 22 22 23 25 -1

它应在-1处立即停止扫描仪,并输出以下阵列:

12 22 22 23 24 -1

我试过的

由于无法为标准数组指定固定大小的数组,因此我使用了一个数组列表,它可以自由地从scanner对象附加尽可能多的值。一旦我了解了这一步,我就对输入的任何整数进行了简单的用户验证,如下所示:

public static void main(String[] args) {
   //  Initiate scanner and a new array
   Scanner scnr = new Scanner(System.in);
   ArrayList<Integer> userValues = new ArrayList<Integer>();

   System.out.print("Enter numbers: ");

   //  While the scanner reads an integer, add integers to the array list
   while (scnr.hasNextInt()) {
      userValues.add(scnr.nextInt());
   }

   //  Print out the array list
   System.out.println(userValues);
 }


顶部的输入和输出如下所示。 输入

1 2 3 45 32 1 L

输出

[1, 2, 3, 45, 32, 1]


这只适用于基本整数验证,并停止向数组中输入字符串或其他数据类型。我似乎不知道如何停止扫描对象并存储整个阵列。以下代码是我试图解决这个问题的代码:

public static void main(String[] args) {
   //  Initiate scanner and new array
   Scanner scnr = new Scanner(System.in);
   ArrayList<Integer> userValues = new ArrayList<Integer>();
   boolean isPositive = true;

   System.out.print("Enter numbers: ");

   //  TODO: Once the user enters a value less than 0, break the loop
  while(scnr.hasNextInt() && isPositive) {
     if(scnr.nextInt() < 0) {
       isPositive = false;
     } else {
       userValues.add(scnr.nextInt());
     }
   }
   System.out.println(userValues);
}

在失败的尝试中,这不起作用,给了我奇怪的输出,我无法理解


输入

1 23 45 -1 -1

输出

[23, -1]



谢谢你的帮助


共 (2) 个答案

  1. # 1 楼答案

    在循环开始时检查-ve输入怎么样

        int val;
        while ((val = scnr.nextInt()) >= 0){
            userValues.add(val);
        }
    
        // Print out the array list
        System.out.println(userValues);
    
  2. # 2 楼答案

    你可以简化一点

    https://ideone.com/GmZ7nH#stdin

     Scanner scnr = new Scanner(System.in);
       ArrayList<Integer> userValues = new ArrayList<Integer>();
       System.out.print("Enter numbers: ");
    
       //  TODO: Once the user enters a value less than 0, break the loop
      while(scnr.hasNextInt()) {
         int temp = scnr.nextInt(); 
         if( temp < 0) {
           break;
         } else {
           userValues.add(temp);
         }
       }
       System.out.println(userValues);
        }